import { defineStore } from 'pinia';
import { login, register, getCurrentUser } from '@/api/auth';
import { ElMessage } from 'element-plus';
import { handleApiError } from '@/utils/errorHandler';

export const useUserStore = defineStore('user', {
  state: () => ({
    user: JSON.parse(localStorage.getItem('user')) || null,
    token: localStorage.getItem('token') || null,
    loading: false,
    error: null
  }),
  
  getters: {
    isLoggedIn: (state) => !!state.token,
    userInfo: (state) => state.user
  },
  
  actions: {
    async login(credentials) {
      this.loading = true;
      this.error = null;
      
      try {
        const response = await login(credentials);

        // 检查响应状态码
        if (response && response.code === 200 && response.data) {
          console.log('登录成功，处理用户数据');
          console.log(response);
          
          // 保存token和用户信息
          this.token = response.data.token;
          this.user = response.data.user;
          
          // 保存到本地存储
          localStorage.setItem('token', this.token);
          localStorage.setItem('user', JSON.stringify(this.user));
          
          ElMessage.success('登录成功');
          return response.data;
        } else {
          // 登录失败 - 直接使用后端返回的错误消息
          console.log('登录失败，响应码:', response?.code);
          console.log('登录失败，错误消息:', response?.message);
          
          // 使用响应中的message字段作为错误消息
          const errorMsg = response ? (response.message || '登录失败') : '服务器无响应';
          this.error = errorMsg;
          
          throw new Error(errorMsg);
        }
      } catch (error) {
        console.error('登录过程中出现错误:', error);
        this.error = handleApiError(error, '登录失败，请检查用户名和密码');
        throw new Error(this.error);
      } finally {
        this.loading = false;
      }
    },
    
    async register(userData) {
      this.loading = true;
      this.error = null;
      try {
        // 尝试调用真实API
        try {
          const response = await register(userData);
          
          if (response.code === 200) {
            ElMessage.success('注册成功，请登录');
            return response.data;
          } else {
            throw new Error(response.message || '注册失败');
          }
        } catch (apiError) {
          console.error('API注册失败:', apiError);
          
          // 如果是开发环境，可以使用模拟数据
          if (import.meta.env.DEV) {
            console.log('使用模拟注册');
            ElMessage.success('模拟注册成功，请登录');
            return { success: true };
          } else {
            throw apiError;
          }
        }
      } catch (error) {
        this.error = error.message || '注册失败，请稍后再试';
        ElMessage.error(this.error);
        throw error;
      } finally {
        this.loading = false;
      }
    },
    
    async fetchCurrentUser() {
      if (!this.token) return null;
      
      this.loading = true;
      try {
        const userData = await getCurrentUser();
        this.user = userData;
        localStorage.setItem('user', JSON.stringify(userData));
        return userData;
      } catch (error) {
        this.logout();
        throw error;
      } finally {
        this.loading = false;
      }
    },
    
    setUserData(data) {
      this.token = data.token;
      this.user = data.user;
      localStorage.setItem('token', data.token);
      localStorage.setItem('user', JSON.stringify(data.user));
    },
    
    logout() {
      // 清除状态
      this.token = null;
      this.user = null;
      
      // 清除本地存储
      localStorage.removeItem('token');
      localStorage.removeItem('user');
      
      ElMessage.success('已退出登录');
    },
    
    // 更新用户信息
    updateUser(userData) {
      this.user = { ...this.user, ...userData };
      localStorage.setItem('user', JSON.stringify(this.user));
    },
    
    // 在用户存储中添加或修改更新用户资料的方法
    async updateUserProfile(userData) {
      try {
        const response = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/user/update`, {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${localStorage.getItem('token')}`
          },
          body: JSON.stringify(userData)
        });
        
        const data = await response.json();
        
        if (data.code === 200) {
          // 更新本地存储的用户信息
          this.user = { ...this.user, ...userData };
          localStorage.setItem('user', JSON.stringify(this.user));
          return data;
        } else {
          throw new Error(data.message || '更新用户资料失败');
        }
      } catch (error) {
        console.error('更新用户资料失败:', error);
        throw error;
      }
    }
  }
}); 